package com.awa.usercenter.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.awa.usercenter.common.BaseResponse;
import com.awa.usercenter.common.Code;
import com.awa.usercenter.common.utils.JwtUtils;
import com.awa.usercenter.common.utils.SmsUtil;
import com.awa.usercenter.exception.BusinessException;
import com.awa.usercenter.mapper.UserMapper;
import com.awa.usercenter.model.code.CodeLoginRequest;
import com.awa.usercenter.model.domain.User;
import com.awa.usercenter.model.domain.request.ForgetPassRequest;
import com.awa.usercenter.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.awa.usercenter.constant.UserConstant.USER_LOGIN_STATE;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private JwtUtils jwtUtils;
    private final AuthenticationManager authenticationManager;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    CodeUserServiceImpl codeUserService;
    @Autowired
    UserMapper userMapper;

    public UserServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    @Override
    public void sendsms(String userPhone, String code) throws ClientException {
        SmsUtil.sendSms(userPhone, "SMS_465086053", code);
    }

    @Override
    public void userRegister(String userPhone, String userPassword, String code) {
        String token = codeUserService.userCodeLoginToken(userPhone, code);
        if(token!=null)
        {
            // 开始注册
            // todo
            User user = new User();
            user.setPhone(userPhone);
            user.setPassword(userPassword);
            // 生成id等业务逻辑
            userMapper.insert(user);
            // 赋予user角色，授权
        }
        else throw new BusinessException(Code.SYSTEM_ERROR);
    }

    @Override
    public String userLoginToken(String userAccount, String userPassword) {
        // 校验
        if(StringUtils.isAnyBlank(userAccount, userPassword)){
            throw new BusinessException(Code.NULL_ERROR);
        }

        // 账户长度不小于4位
        if(userAccount.length() < 4){
            throw new BusinessException(Code.PARAMS_ERROR, "手机号不得小于4位");
        }

        // 密码长度不小于4位
        if(userPassword.length() < 4){
            throw new BusinessException(Code.PARAMS_ERROR, "用户密码不得小于8位");
        }
        // 账户不包含特殊字符
        String validPattern = "\\w{6,}";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(!matcher.find()){
            return null;
        }
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userAccount, userPassword);
        Authentication authenticate = null;
        try{
            authenticate = authenticationManager.authenticate(authentication);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        }catch(BadCredentialsException e)
        {
            log.error("用户名或密码错误");
            throw new BusinessException(Code.PARAMS_ERROR, "用户名或密码错误");
        }

        User principal = (User) authenticate.getPrincipal();
        principal.setPassword("");
        HashMap<String,Object> map = new HashMap<>();
        map.put("userId",principal.getUserId());
        map.put("phone",principal.getPhone());
        map.put("roles",principal.getRoleSet());
        String token = jwtUtils.createToken(map);
        // 存入redis
        redisTemplate.opsForValue().set(token,principal);
        return token;
    }
    @Override
    public int userLogout(HttpServletRequest request) {
        // token 登出
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
    @Override
    public BaseResponse<String> forgetPassHandler(ForgetPassRequest forgetPassRequest) {
        //校验手机号是否存在
        String userPhone = forgetPassRequest.getUserPhone();
//        validatePhoneExit(userPhone);

        //todo 忘记密码 部分需要等待腾讯云通过补充的代码
        //校验校验码是否正确

//        validatePhoneCode(forgetPassRequest.getUserCode(), userPhone);
        //根据手机号修改用户密码
        String userPassword = forgetPassRequest.getUserPassword();
        // 密码长度不小于4位
        if(userPassword.length() < 4){
            throw new BusinessException(Code.PARAMS_ERROR, "用户密码不得小于8位");
        }
        //转换密码为加密之后的密码
//        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
//        Long aLong = userMapper.updatePwd(encryptPassword, userPhone);
//        if(aLong<0){
//            throw new BusinessException(Code.PARAMS_ERROR, "密码修改失败");
//        }
        return null;
    }
}




